package com.zlyx.easy.redis.config;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import com.zlyx.easy.redis.service.RedisKeyExpirationService;

/**
 * <p>
 * Redis键过期监听器配置类
 * </p>
 *
 * @author 赵光
 * @version v1.0
 */
public class RedisListenerConfig {

	private static final Logger logger = LoggerFactory.getLogger(CacheConfig.class);

	@Autowired
	public List<RedisKeyExpirationService> redisKeyExpirationServices;

	@Bean
	@ConditionalOnMissingBean
	public RedisMessageListenerContainer configRedisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		return container;
	}

	@Bean
	@ConditionalOnMissingBean
	public KeyExpirationEventMessageListener configKeyExpirationEventMessageListener(
			RedisMessageListenerContainer container) {
		return new KeyExpirationEventMessageListener(container) {
			@Override
			public void onMessage(Message message, byte[] pattern) {
				String expiredKey = message.toString();
				logger.debug("过期的key.{}", expiredKey);
				if (redisKeyExpirationServices == null || redisKeyExpirationServices.isEmpty()) {
					logger.warn("redisKeyExpirationServices is not exist");
					return;
				}
				redisKeyExpirationServices.forEach(redisKeyExpirationService -> {
					redisKeyExpirationService.doProcess(expiredKey, pattern);
				});
			}
		};
	}
}